SDK=macosx
TARGET=arm64-apple-macos12.0

CC=xcrun -sdk $(SDK) clang

WARNINGS=-Wall -Wpedantic -Werror
NO_WARNINGS=-Wno-gnu-statement-expression -Wno-gnu-zero-variadic-macro-arguments -Wno-gnu-empty-struct -Wno-dollar-in-identifier-extension -Wno-language-extension-token -Wno-zero-length-array
CFLAGS=-target $(TARGET) -D__arm64__ -D__aarch64__ -D__DARWIN_OPAQUE_ARM_THREAD_STATE64 -nostdlib -O0 $(WARNINGS) $(NO_WARNINGS)
LDFLAGS=-target $(TARGET) -nostdlib -dead-strip -fpie -lSystem

MIG_SOURCES=$(wildcard Sources/*.defs)
MIG_GENERATED_SOURCES=$(addprefix Sources/generated/,$(patsubst %.defs,%.c,$(notdir $(MIG_SOURCES))))
MIG_GENERATED_HEADERS=$(addprefix Sources/generated/,$(patsubst %.defs,%.h,$(notdir $(MIG_SOURCES))))

SOURCES=$(wildcard Sources/*.c) $(wildcard Sources/*.S) $(MIG_GENERATED_SOURCES)
OBJS=$(addprefix build/,$(patsubst %.c,%.o,$(patsubst %.S,%.o,$(SOURCES))))

HEADERS=$(wildcard Sources/*.h) $(MIG_GENERATED_HEADERS)

OUTPUT_DIRS=$(dir $(OBJS))

all: oobPCI

.PHONY: all build_clean clean

oobPCI: build/oobPCI
	install_name_tool -change /usr/lib/libSystem.B.dylib /System/DriverKit/System/Library/Frameworks/DriverKit.framework/DriverKit $<
	../../Tools/Exe2Driver/Exe2Driver $< $@
	@chmod +x $@
	@ldid -SoobPCI.entitlements $@

build/oobPCI: ensure_output_dirs $(MIG_GENERATED_SOURCES) $(MIG_GENERATED_HEADERS) $(OBJS)
	$(CC) -o $@ $(OBJS) $(LDFLAGS)

build/%.o: %.c $(HEADERS)
	$(CC) -c -o $@ $< $(CFLAGS)

build/%.o: %.S $(HEADERS)
	$(CC) -c -o $@ $< $(CFLAGS) --std=c++11
	
Sources/generated/%.h Sources/generated/%.c: Sources/%.defs
	mig -user $(patsubst %.h,%.c,$@) -header $(patsubst %.c,%.h,$@) -server /dev/null -sheader /dev/null $<

ensure_output_dirs:
	mkdir -p $(OUTPUT_DIRS)

build_clean:
	rm -rf build

clean: build_clean
	rm -f oobPCI
